from math import floor

from duckserver.models import User, Follow, Comment, Work, Likerelation, Payrelation, EmailVerify, Room
import datetime
import time
from django.conf import settings

from duckserver.service.duckPowerEgg import refreshPower, costPower, costEgg, getPower, getEgg
from duckserver.service.record import getDailyStudyTime
# from duckserver.service.work import feedback

def getuser(userid):
    response = {'uid': 0, 'username': '', 'ok': 0, 'msg': ''}
    user = User.objects.get(userid=userid)
    response["uid"] = user.userid
    response["username"] = user.username
    response["ok"] = 1

    return response


def adduser(username):
    response = {'uid': 0, 'username': '', 'ok': 0, 'msg': ''}
    user = User(username=username)
    user.save()
    response["uid"] = user.userid
    response["username"] = user.username
    response["ok"] = 1

    return response


# 注册
def signup(username, password, email, verifycode):
    response = {'userid': 0, 'ok': 0, 'msg': ''}
    u = User.objects.filter(username=username)
    if len(u) != 0:
        response['msg'] = "用户名已存在"
        return response

    # 校验验证码
    mails = EmailVerify.objects.filter(email=email)
    if len(mails) == 0:
        response['msg'] = "该邮箱不存在"
        return response

    mail = mails[0]
    now = datetime.datetime.now()

    if mail.verifyCode != int(verifycode):
        response['msg'] = "验证码错误"
        return response

    if now - mail.createtime > datetime.timedelta(minutes=30):
        response['msg'] = "验证码已失效"
        return response

    user = User(username=username, password=password, email=email)
    user.save()
    response['userid'] = user.userid
    response["ok"] = 1
    return response


# 登录(邮箱或用户名)
def login(username, password):
    response = {'userid': 0, 'ok': 0, 'msg': ''}
    u = User.objects.filter(username=username, password=password)
    e = User.objects.filter(email=username, password=password)
    if len(u) == 0 and len(e) == 0:
        response['msg'] = "用户名或密码错误"
        return response
    user = None
    if len(u) != 0:
        user = u[0]
    else:
        user = e[0]
    response['userid'] = user.userid
    response['status'] = user.status
    response['isadministrator'] = user.isadministator

    response['userinfo'] = getUserInfo(user.userid, user.userid)
    response["ok"] = 1
    return response


# 获取用户信息
def getUserInfo(userid, myid):
    '''
    userid: 需要获取信息的用户
    myid: 发送请求的用户
    '''
    response = {'userid': 0, 'ok': 0, 'msg': ''}
    refreshPower(userid)
    user = User.objects.get(userid=userid)

    me = User.objects.get(userid=myid)
    room = Room.objects.filter(userid=user)

    relation = Follow.objects.filter(userid=userid, follower=me)

    likerelation = Likerelation.objects.filter(userid=user)

    if len(relation) == 0:
        response['isfollowed'] = False
    else:
        response['isfollowed'] = True

    response['userid'] = user.userid
    response['username'] = user.username
    response['headImage'] = settings.ROOT_URL + user.headImage.url
    response['fansNum'] = user.fansNum
    response['careNum'] = user.careNum
    response['groupNum'] = user.groupNum
    response['power'] = floor(user.power)
    response['recoverTime'] = user.recoverTime
    response['credit'] = user.credit
    response['status'] = user.status
    response['isAdministrator'] = user.isadministator
    response['email'] = user.email
    response['sex'] = user.sex
    works = Work.objects.filter(userid=user)
    response['workNum'] = len(works)
    if len(room) == 0:
        response['inRoom'] = 0
    else:
        response['inRoom'] = 1
        response['roomname'] = room[0].roomname
        response['roomid'] = room[0].roomid
    response['studytime'] = getDailyStudyTime(userid)
    response['thumbsup'] = len(likerelation)
    response["ok"] = 1
    return response


# 更新用户信息 type 0,1,2,3分别对应修改用户名、密码、头像、性别
def updateUserInfo(userid, username, password, imgList, sex, type):
    type = int(type)
    response = {'userid': 0, 'ok': 0, 'msg': ''}
    user = User.objects.get(userid=userid)
    if type == 0:
        users = User.objects.filter(username=username)
        if len(users) != 0:
            response['msg'] = "该用户名已存在"
            return response
        if username is None or username == "":
            response['msg'] = "用户名不能为空"
            return response
        user.username = username
    elif type == 1:
        if password is None or len(password) < 6:
            response['msg'] = "密码过短"
            return response
        user.password = password
    elif type == 2:
        if len(imgList) != 0:
            user.headImage = imgList[0]
            user.save()
            response['imgurl'] = settings.ROOT_URL + user.headImage.url
    elif type == 3:
        user.sex = int(sex)

    user.save()
    response["ok"] = 1
    response["userid"] = userid
    return response


# 5 37 14 15 16

# 5  获取粉丝、关注列表
def getFansCareList(userid):
    response = {'fans': [],'care':[], 'ok': 0, 'msg': ''}
    fans = []
    care = []
    followList = Follow.objects.filter(userid=userid)
    careList = Follow.objects.filter(follower=userid)
    for follower in followList:
        data = {}
        data['userid'] = follower.follower.userid
        data['username'] = follower.follower.username
        data['headImage'] = settings.ROOT_URL + follower.follower.headImage.url
        fans.append(data)

    for carer in careList:
        data = {}
        data['userid'] = carer.userid.userid
        data['username'] = carer.userid.username
        data['headImage'] = settings.ROOT_URL + carer.userid.headImage.url
        care.append(data)

    response['fans'] = fans
    response['care'] = care
    response['ok'] = 1
    return response


# 37 关注/取消
def follow(userid,careid):
    response = {'ok': 0, 'msg': ''}
    user = User.objects.get(userid=userid)
    cared = User.objects.get(userid=careid)
    relation = Follow.objects.filter(userid=careid,follower=userid)
    # 表中无关系，说明是关注操作
    if len(relation) == 0:
        newRelation = Follow(userid=cared, follower=user)
        newRelation.save()

        user.careNum = user.careNum + 1
        user.save()

        cared.fansNum = cared.fansNum + 1
        cared.save()
        response['status'] = 1
    # 否则是取消关注
    else:
        relation[0].delete()

        user.careNum = user.careNum - 1
        user.save()

        cared.fansNum = cared.fansNum - 1
        cared.save()
        response['status'] = 0
    response['ok'] = 1
    return response


# 15 添加评论 原帖子的commentparentid用@开头
def addComment(commentparentid, userid, content, rootknot):
    response = {'ok': 0, 'msg': ''}
    if costPower(userid, 5):
        user = User.objects.get(userid=userid)
        parentuser = User
        if commentparentid[0] == '@':
            parentuser = Work.objects.get(workid = commentparentid[1:]).userid
        else:
            parentuser = Comment.objects.get(commentid=commentparentid).userid
        work = Work.objects.get(workid=rootknot)
        newComment = Comment(commentparentid=commentparentid, parentuserid = parentuser,userid=user, content=content, rootknot=work)
        newComment.save()
        work.commentnum += 1
        work.save()
        response['ok'] = 1
        response['commentId'] = newComment.commentid
    else:
        response['msg'] = "鸭力不足"
    return response


# 16 点赞取消
def thumbUp(userid, workid):
    response = {'ok': 0, 'msg': ''}
    user = User.objects.get(userid=userid)
    work = Work.objects.get(workid=workid)
    relation = Likerelation.objects.filter(userid=userid, workid=workid)
    # 表中无关系，说明是点赞操作
    if len(relation) == 0:
        if costPower(userid, 5):
            newRelation = Likerelation(userid=user, workid=work)
            newRelation.save()

            work.attitudenum += 1
            work.save()
            getEgg(work.userid.userid, 1)

            # 判断是否在推荐列表
            from duckserver.service.work import feedback, getRecommendedPost
            recommendList = getRecommendedPost(userid, 20)
            inRecommend = False
            for item in recommendList['workList']:
                # print(item['workid'])
                if item['workid'] == int(workid):
                    inRecommend = True
            if inRecommend:
                feedback(userid, workid)

            response['attitudenum'] = work.attitudenum
            response['status'] = 1
        else:
            response['msg'] = "鸭力不足"
            return response
    # 否则是取消点赞
    else:
        relation[0].delete()

        work.attitudenum -= 1
        work.save()

        response['attitudenum'] = work.attitudenum
        response['status'] = 0
    response['ok'] = 1
    return response


# 17 购买作品
def purchaseWork(userid, workid):
    response = {'ok': 0, 'msg': ''}
    buyer = User.objects.get(userid=userid)
    work = Work.objects.get(workid=workid)
    if buyer.credit < work.getpaid:
        response['msg'] = "余额不足"
    else:
        buyer.credit -= work.getpaid
        work.userid.credit += work.getpaid
        newRelation = Payrelation(userid=buyer, workid=work)
        newRelation.save()
        buyer.save()
        work.userid.save()
        response['ok'] = 1
        response['msg'] = '购买成功'

        # 顺便返回原文
        response['detailContent'] = work.text
    return response


# 更换用户头像
def changeUserHeadImg(userid, img):
    response = {'ok': 0, 'msg': ''}
    user = User.objects.get(userid=userid)
    user.headImage = img
    user.save()
    response['headimg'] = settings.ROOT_URL + user.headImage.url
    response['ok'] = 1
    response['msg'] = '头像更换成功'
    return response


# 购买鸭力，用户前端自定义购买数量
def purchasePower(userid, price):
    response = {'ok': 0, 'msg': ''}
    if costEgg(userid, price):
        getPower(userid, price)
    else:
        response['msg'] = "鸭蛋不足"
    return response